﻿//-----------------------------------------------------------------------
// <copyright file="ExecutorFactory.cs" company="tuliprules.org">
//     Copyright (c) 2010 tuplelister, tuliprules.org.
// </copyright>
// <summary>This is the ExecutorFactory class.</summary>
//-----------------------------------------------------------------------

namespace Tulip.Rules.CodeGen
{
    using System;
    using System.IO;
    using System.Windows.Markup;
    using Tulip.Engine.Models.ClosedWorld;
    using Tulip.Engine;

    /// <summary>
    /// An executor factory for Tulip rules.
    /// </summary>
    public class ExecutorFactory : Tulip.Rules.IExecutorFactory
    {
        // TODO: Remove the following two lines
        private const string modelPath = @"E:\Tulip\Rules\CodeGen\Development\model.xaml";
        private const string modelOutPath = @"E:\Tulip\Rules\CodeGen\Development\model.xml";

        private ModelTemplates modelTemplates = new ModelTemplates();

        /// <summary>
        /// Returns an instance of an executor for the given Tulip model.
        /// </summary>
        /// <param name="model">The Tulip model.</param>
        /// <returns>
        /// An executor the given Tulip model.
        /// </returns>
        public Executor GetExecutor(Items model)
        {
            //TODO: Remove the following two lines
            model = LoadModel(modelPath);
            SaveModel(model);

            var generator = new Generator();

            this.modelTemplates.EntityTupleTemplate = new Templates.EntityTupleTemplate(); 
            return generator.GenerateExecutor(model, this.modelTemplates);
        }


        //TODO: Remove the following method
        private  Items LoadModel(string fromFile)
        {
            var xamlFile = new FileStream(fromFile, FileMode.Open, FileAccess.Read);
            var model = (Items)XamlReader.Load(xamlFile);
            return model;
        }

        //TODO: Remove the following method
        private void SaveModel(Items myModel)
        {
            var modelOut = XamlWriter.Save(myModel);
            Console.WriteLine(modelOut);
            var xamlFile = new FileStream(modelOutPath, FileMode.Create, FileAccess.Write);
            XamlWriter.Save(myModel, xamlFile);
            xamlFile.Close();
        }
    }
}
